<?php

namespace App\Models\Admin;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Model;
use App\Common\ValidateHandler;
use App\Models\Admin\Grade;
use Config;
use App\Tools\src\YopRequest;
use App\Tools\src\YopRsaClient;

class PayConfig extends BaseModel
{
    protected $fillable = [
        'id', 'store_id', 'type', 'merchant_id', 'pay_secret',
        'app_id', 'app_secret', 'yop_merchantno',
        'created_at', 'updated_at'
    ];
    const PAYINI = [
        'type' => 1,
        'merchantId' => '',
        'pay_secret' => '',
        'appId' => '',
        'appSecret' => '',
        'yopMerchantNo' => ''
    ];
    // [验证]初始化指定店铺 的 支付配置信息
    public function analyPay($id)
    {
        $Grade = new Grade;
        $validateGrade = $Grade->validateGrade($id);
        if($validateGrade['code'] !== 20000){
            return $validateGrade;
        }else{
            $storeGarde = $validateGrade['data']['data'];
        }
        if (empty($storeGarde)) {
            return $this->error(['info' => '['.$id.']店铺等级信息不存在!请先完善店铺等级信息!']);
        } else {
            return $this->getPay($id);
        }
    }
    // 获取指定店铺的初始化数据
    public function getPay($id)
    {
        $payInfo = [];
        $pay = $this->where('store_id', $id)->first();
        if (empty($pay)) {
            $payInfo = self::PAYINI;
        } else {
            $payInfo['type'] = $pay['type'];
            $payInfo['merchantId'] = $pay['merchant_id'];
            $payInfo['paySecret'] = $pay['pay_secret'];
            $payInfo['appId'] = $pay['app_id'];
            $payInfo['appSecret'] = $pay['app_secret'];
            $payInfo['yopMerchantNo'] = $pay['yop_merchantno'];
        }
        $rechargeInfo = Config::get("const.recharge_select");
        return $this->success(['data' => $payInfo, 'options' => $rechargeInfo, 'info' => '['.$id.']店铺支付配置信息初始化成功!']);
    }
    // 提交支付配置数据
    public function insertAnlayArr($id, $data)
    {
        // 验证 店铺 / 店铺等级信息
        $analyPay = $this->analyPay($id);
        if ($analyPay['code'] != 20000) {
            return $analyPay;
        }
        // 验证 并 得到需要插入的数据格式
        $insertPay = $this->foreachGet($data, $id);
        if ($insertPay['code'] != 20000) {
            return $insertPay;
        }
        // 验证支付配置数据是否存在 , 并以此决定 插入 或 更新
        $payGold = $this->payGold($id);
        if ($payGold) {
            $back = $this->where('store_id', $id)->update($insertPay['data']['data']);
        } else {
            $back = $this->create($insertPay['data']['data']);
        }
        $result = $this->ybWechatConfigAdd($insertPay['data']['data']);
        if (!$back && $result->code != 00000) {
            return $this->error(['data' =>  $insertPay['data']['data'],'info' => '['.$id.']店铺支付配置信息创建失败!']);
        }else{
            return $this->success(['data' =>  $insertPay['data']['data'], 'info' => '['.$id.']店铺支付配置信息创建成功!']);
        }
    }

    //通过易宝配置微信公众号支付授权目录，appid等信息
    public function ybWechatConfigAdd($payConfig){
        $yopConfig = Config::get("const.yop_config");
        /*商户私钥*/
        $private_key = $yopConfig["private_key"];
        $appKey = $yopConfig["appKey"];
        $parentMerchantNo = $yopConfig["parentMerchantNo"];
        $merchantNo = $payConfig["yop_merchantno"];
        $tradeAuthDirList = '["'.env("APP_WEB_URL").'/"]';
        $appIdList = '[{"appId":"'.$payConfig["app_id"].'","appSecret":"'.$payConfig["app_secret"].'","appIdType":"OFFICIAL_ACCOUNT","subscribeAppId":"subscribeAppId"}]';

        $request = new YopRequest($appKey, $private_key);
        
        //加入请求参数
        $request->addParam("parentMerchantNo", $parentMerchantNo);//发起方商户编号
        $request->addParam("merchantNo", $merchantNo);//商户编号
        $request->addParam("tradeAuthDirList", $tradeAuthDirList);//支付授权目录列表
        $request->addParam("appIdList", $appIdList);//支付appId目录列表    JSON字符串；

        //提交Post请求
        $response = YopRsaClient::post("/rest/v2.0/aggpay/wechat-config/add", $request);
        return $response->result;
    }

    // 验证此店铺支付配置是否存在
    public function payGold($id)
    {
        return $this->where('store_id', $id)->first();
    }
    // 遍历前台数据 形成插入的内容
    public function foreachGet($data, $id)
    {
        $insert = [];
        $res = $this->validate($data);
        if (!$res['res']) {
            return $this->error(['info' => $res['info']]);
        }
        $insert['store_id'] = $id;
        $insert['type'] = $data['type'];
        $insert['merchant_id'] = $data['merchantId'];
        $insert['pay_secret'] = $data['paySecret'];
        $insert['app_id'] = $data['appId'];
        $insert['app_secret'] = $data['appSecret'];
        $insert['yop_merchantno'] = (int)$data['yopMerchantNo'];

        return $this->success(['data' =>  $insert, 'info' => '插入数据验证成功!']);
    }
    //店铺会员等级表 字段合法性验证
    private function validate($data)
    {
        $arr = [
            0 => [
                'name' => '充值类型',
                'value' => $data['type'],
                'func' => 'range_status',
                'arr' => Config::get("const.recharge_type")
            ],
            1 => [
                'name' => '商户ID',
                'value' => $data['merchantId'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 100
            ],
            2 => [
                'name' => '支付秘钥',
                'value' => $data['paySecret'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 200
            ],
            3 => [
                'name' => '公众号ID',
                'value' => $data['appId'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 200
            ],
            4 => [
                'name' => '公众号秘钥',
                'value' => $data['appSecret'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 200
            ],
            5 => [
                'name' => '易宝商编号',
                'value' => $data['yopMerchantNo'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 100
            ]
        ];
        return ValidateHandler::do($arr);
    }
}
